import { citys, trim } from '../index'

// 校验是否二代身份证号
export const isIdCard = (id: string) => {
  if (typeof id !== 'string') throw new Error(`arguments[0] is required string but got ${id}`)

  id = trim(id)

  if (!id) return false

  if (id.length !== 18) return false

  if (!/(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(id)) return false

  const city = citys[id.slice(0, 2)]

  if (city) return false

  const list = id.split('')

  // 加权因子
  const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]

  // 校验位
  const parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2, 'x']

  let sum = 0
  let ai = 0
  let wi = 0

  let i = 0

  while (i < 17) {
    ai = +list[i]
    wi = factor[i]
    sum += ai * wi

    i++
  }

  // ∑(ai×Wi)(mod 11)
  return `${parity[sum % 11]}` === `${list[17]}`
}